package com.jackrain.nea.core.service;

import com.alibaba.dubbo.config.annotation.Service;
import com.jackrain.nea.core.entity.AdTableModel;
import com.jackrain.nea.core.mapper.AdColumnMapper;
import com.jackrain.nea.core.mapper.MapperDDL;
import com.jackrain.nea.core.utility.CommandData;
import com.jackrain.nea.core.api.AdColumnDelCmd;
import com.jackrain.nea.core.mapper.AdTableMapper;
import com.jackrain.nea.core.mapper.AdTableSqlMapper;
import com.jackrain.nea.exception.NDSException;
import com.jackrain.nea.sys.CommandAdapter;
import com.jackrain.nea.util.Tools;
import com.jackrain.nea.util.ValueHolder;
import com.jackrain.nea.web.query.QuerySession;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.sql.Timestamp;

@Slf4j
@Component
@Service(protocol = "dubbo", validation = "true", version = "1.0", group = "ad")
public class AdColumnDelCmdImpl extends CommandAdapter implements AdColumnDelCmd {

    @Autowired
    private AdTableMapper adTableMapper;
    @Autowired
    private AdColumnMapper adColumnMapper;
    @Autowired
    private AdTableSqlMapper adTableSqlMapper;
    @Autowired
    private MapperDDL mapperDDL;

    @Override
    @Transactional
    public ValueHolder execute(QuerySession session) throws NDSException {
        CommandData data = new CommandData(session);
        if (!data.isDeleteMainTable()) {
            throw data.notSupported();
        }

        long id = data.getObjId();
        AdTableModel table = adTableMapper.select(id);
        int tableid = Tools.getInt(table.getAdTableId(), -1);
        String colname = table.getDbname();
        String tabname = table.getName();

        if (!data.checkVirtual(colname)) {
            int pcount = adColumnMapper.countWithRefColumn(id);
            if (pcount > 0) {
                throw data.exception("存在对该字段的外键引用，不能删除！");
            }
            pcount = adColumnMapper.count(id, id);

            if (pcount > 0) {
                throw data.exception("该字段的是表的PK/AK，请重新定义PK/AK再删除！");
            }

            pcount = adTableMapper.columnCount(tabname, colname);
            if (pcount > 0) {
                mapperDDL.dropColumn(tabname, colname);
                adTableSqlMapper.DDLLog(tableid,"alter table " + tabname + " drop " + colname);
            }
        }

        adTableMapper.updateModifieddate(new Timestamp(System.currentTimeMillis()),tableid);


        //delete ad_table
        adColumnMapper.deleteWithid(id);

        return data.success();
    }
}
